package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"encoding/hex"
	"io"
)

var (
	// 默认密钥和IV
	DefaultKey = []byte("9876543210abcdef")
	DefaultIV  = []byte("0123456789abcdef")
)

// AES加密工具
type AESCrypto struct {
	key []byte
	iv  []byte
}

// 创建新的AES加密工具
func NewAESCrypto(key, iv []byte) *AESCrypto {
	if key == nil {
		key = DefaultKey
	}
	if iv == nil {
		iv = DefaultIV
	}
	return &AESCrypto{
		key: key,
		iv:  iv,
	}
}

// AES-CBC加密
func (a *AESCrypto) Encrypt(plaintext []byte) (string, error) {
	block, err := aes.NewCipher(a.key)
	if err != nil {
		return "", err
	}

	// 填充数据
	plaintext = pkcs7Padding(plaintext, block.BlockSize())

	// 创建加密器
	mode := cipher.NewCBCEncrypter(block, a.iv)

	// 加密数据
	ciphertext := make([]byte, len(plaintext))
	mode.CryptBlocks(ciphertext, plaintext)

	// 转换为十六进制字符串
	return hex.EncodeToString(ciphertext), nil
}

// AES-CBC解密
func (a *AESCrypto) Decrypt(cipherHex string) ([]byte, error) {
	// 解码十六进制字符串
	ciphertext, err := hex.DecodeString(cipherHex)
	if err != nil {
		return nil, err
	}

	block, err := aes.NewCipher(a.key)
	if err != nil {
		return nil, err
	}

	// 创建解密器
	mode := cipher.NewCBCDecrypter(block, a.iv)

	// 解密数据
	plaintext := make([]byte, len(ciphertext))
	mode.CryptBlocks(plaintext, ciphertext)

	// 去除填充
	plaintext = pkcs7UnPadding(plaintext)

	return plaintext, nil
}

// Base64编码
func (a *AESCrypto) EncryptToBase64(plaintext []byte) (string, error) {
	hexStr, err := a.Encrypt(plaintext)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString([]byte(hexStr)), nil
}

// Base64解码
func (a *AESCrypto) DecryptFromBase64(base64Str string) ([]byte, error) {
	hexBytes, err := base64.StdEncoding.DecodeString(base64Str)
	if err != nil {
		return nil, err
	}
	return a.Decrypt(string(hexBytes))
}

// PKCS7填充
func pkcs7Padding(data []byte, blockSize int) []byte {
	padding := blockSize - len(data)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(data, padtext...)
}

// PKCS7去除填充
func pkcs7UnPadding(data []byte) []byte {
	length := len(data)
	unpadding := int(data[length-1])
	return data[:(length - unpadding)]
}

// GenerateAESKey 生成随机的AES密钥
func GenerateAESKey() string {
	key := make([]byte, 32) // 256位密钥
	if _, err := io.ReadFull(rand.Reader, key); err != nil {
		return "qxz56cI5VN4U48VZvrErbS91CIuHwJRgpePbjUtbzdO"
	}
	return base64.StdEncoding.EncodeToString(key)
}
